package com.itqian.interceptors;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.itqian.common.utils.JWTUtils;
import com.itqian.system.entity.Constants;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shishuqian
 * date 2021/12/8
 * time 14:58
 *  JWT登录拦截器
 **/
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader("token");
        System.out.println(token);
        try {
            //验证令牌
            JWTUtils.verify(token);
            //获取请求的资源需要的权限
            String type = request.getServletPath().split("/")[1];
            //获取token中的信息
            DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
            //获取用户的登录身份
            String role = tokenInfo.getClaim("loginRole").asString();
            //验证是否有该资源的身份权限
            if (type.equals(Constants.SELLER)){
                //访问商家相关接口需要商家权限或管理员权限
                if (!role.equals(Constants.SELLER) && !role.equals(Constants.ADMIN)){
                    map.put("msg","当前用户无此接口访问权限...");
                    //将map转为json，使用SpringBoot的默认jackson
                    map.put("code",-1);
                    String json = new ObjectMapper().writeValueAsString(map);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(json);
                    return false;
                }
            }else if (type.equals(Constants.ADMIN)){
                if (!role.equals(Constants.ADMIN)){
                    map.put("msg","当前用户无此接口访问权限...");
                    //将map转为json，使用SpringBoot的默认jackson
                    map.put("code",-1);
                    String json = new ObjectMapper().writeValueAsString(map);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write(json);
                    return false;
                }
            }
            //验证无误，放行请求
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效签名！");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg","token过期！");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg","token算法不一致！");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg","token无效！");
        }
        //将map转为json，使用SpringBoot的默认jackson
        map.put("code",-2);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
        return false;
    }
}
